package com.ncmmall.application.business.distribution;

import com.feijin.commons.lang.Requires;
import com.ncmmall.domain.business.distribution.DistributionCheck;
import com.ncmmall.domain.business.distribution.DistributionCheckRepository;
import com.ncmmall.domain.business.distribution.DistributionGoods;
import com.ncmmall.domain.business.distribution.DistributionGoodsAssign;
import com.ncmmall.domain.business.distribution.DistributionGoodsAssignRepository;
import com.ncmmall.domain.business.distribution.DistributionSetting;
import com.ncmmall.domain.business.distribution.Distributor;
import com.ncmmall.domain.business.distribution.DistributorLevel;
import com.ncmmall.domain.business.distribution.DistributorRepository;
import com.ncmmall.domain.business.distribution.QDistributionGoods;
import com.ncmmall.domain.business.distribution.QDistributionGoodsAssign;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.domain.security.user.WebUserRepository;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分销商管理
 *
 * @author likaikai
 * @date 2020-09-14 15:54:05
 */
@Service
@Transactional
public class DistributorApplication {

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private DistributorRepository distributorRepository;

    @Autowired
    private WebUserRepository webUserRepository;

    @Autowired
    private DistributionCheckRepository distributionCheckRepository;

    @Autowired
    private DistributionSettingApplication distributionSettingApplication;

    @Autowired
    private DistributionGoodsAssignRepository distributionGoodsAssignRepository;

    /**
     * 新增分销商
     *
     * @param params 参数
     */
    public void create(Distributor params) {

        Requires.hasLength(params.getUserIds(), "请选择会员");
        Requires.isTrue(params.getLevel() != null && params.getLevel().getId() != null, "请选择分销商等级");
        Requires.notNull(params.getMicroShop(), "请选择是否开启分销商店");

        List<Long> userIds = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(params.getUserIds()).stream().map(Long::valueOf).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(userIds)) {
            return;
        }

        List<WebUser> users = queryChannelService.findAll(QWebUser.webUser.id.in(userIds), WebUser.class);
        List<DistributionGoods> distributionGoodsList = queryChannelService.findAll(QDistributionGoods.distributionGoods.distributorScope.eq(1), DistributionGoods.class);

        for (WebUser user : users) {

            //用户已经是分销商 跳过
            if (user.getDistributor() != null) {
                continue;
            }

            Distributor distributor = new Distributor();
            distributor.setUser(user);
            distributor.setLevel(params.getLevel());
            distributor.setAccountStatus(1);
            distributor.setSource(2);
            distributor.setMicroShop(params.getMicroShop());
            distributor.setCreateTime(new Timestamp(System.currentTimeMillis()));
            distributorRepository.save(distributor);

            user.setDistributor(distributor);
            webUserRepository.save(user);

            //给每个分销商添加 分销商品池里面的指定所有分销商的商品
            if (CollectionUtils.isNotEmpty(distributionGoodsList)) {
                distributorAddScopeAllGoods(distributionGoodsList, distributor);
            }

        }
    }


    public void disableAccount(Distributor distributor) {
        distributor.setAccountStatus(2);
        distributorRepository.save(distributor);
    }

    public void disableAccounts(List<Distributor> distributors) {
        for (Distributor distributor : distributors) {
            distributor.setAccountStatus(2);
        }
        distributorRepository.save(distributors);
    }

    public void enableAccount(Distributor distributor) {
        distributor.setAccountStatus(1);
        distributorRepository.save(distributor);
    }

    public void enableAccounts(List<Distributor> distributors) {
        for (Distributor distributor : distributors) {
            distributor.setAccountStatus(1);
        }
        distributorRepository.save(distributors);
    }

    public void disableShop(Distributor distributor) {
        distributor.setMicroShop(false);
        distributorRepository.save(distributor);
    }

    public void disableShops(List<Distributor> distributors) {
        for (Distributor distributor : distributors) {
            distributor.setMicroShop(false);
        }
        distributorRepository.save(distributors);
    }

    public void enableShop(Distributor distributor) {
        distributor.setMicroShop(true);
        distributorRepository.save(distributor);
    }

    public void enableShops(List<Distributor> distributors) {
        for (Distributor distributor : distributors) {
            distributor.setMicroShop(true);
        }
        distributorRepository.save(distributors);
    }


    public void modifyLevel(List<Distributor> distributors, DistributorLevel level) {
        for (Distributor distributor : distributors) {
            distributor.setLevel(level);
        }
        distributorRepository.save(distributors);
    }

    public void modifyFather(List<Distributor> distributors, WebUser father) {
        for (Distributor distributor : distributors) {
            WebUser user = distributor.getUser();
            user.setFather(father);
            webUserRepository.save(user);
        }
    }

    /**
     * 免费提交申请
     * 当申请的等级为 applyType = 1 免费加入的时候的申请
     *
     * @return 当前申请是否需要审核 true需要 false不需要
     */
    public boolean apply(WebUser member, DistributorLevel level, Long distributorId) {

        int count = queryChannelService.selectCount("select count(*) from distribution_check where member_id = :mid and checkStatus = 1", ImmutableMap.of("mid", member.getId()));
        Requires.isTrue(count == 0, "请不要重复申请");

        DistributionCheck distributionCheck = new DistributionCheck().setCreateTime(new Timestamp(System.currentTimeMillis()));
        distributionCheck.setMember(member);

        if (member.getFather() == null && distributorId != null) {
            distributionCheck.setDistributorId(distributorId);
        }

        DistributionSetting setting = distributionSettingApplication.findLastSetting();
        distributionCheck.setCheckStatus(setting == null ? 1 : BooleanUtils.isTrue(setting.getDistributorCheck()) ? 2 : 1);
        distributionCheck.setDistributorLevel(level);

        distributionCheck.setActivationFlag(member.getDistributor() != null);

        if (distributionCheck.getCheckStatus() == 2) {
            distributionCheck.setCheckNote("系统默认通过审核");
            //升级无需激活
            if (member.getDistributor() != null) {
                distributionCheck.setActivationFlag(true);
                member.getDistributor().setLevel(distributionCheck.getDistributorLevel());
                distributorRepository.save(member.getDistributor());
            }
            //如果有 绑定father
            if (distributionCheck.getDistributorId() != null) {
                member.setFather(queryChannelService.findOne(QWebUser.webUser.distributor.id.eq(distributorId), WebUser.class));
                webUserRepository.save(member);
            }
        }
        distributionCheckRepository.save(distributionCheck);

        return distributionCheck.getCheckStatus() == 1;
    }

    /**
     * 审核分销商
     */
    public void check(DistributionCheck distributionCheck) {
        DistributionCheck check = queryChannelService.findOne(DistributionCheck.class, distributionCheck.getId());
        check.setCheckStatus(distributionCheck.getCheckStatus())
                .setCheckNote(distributionCheck.getCheckNote())
                .setCheckTime(new Timestamp(System.currentTimeMillis()));

        if (distributionCheck.getCheckStatus() == 2) {
            Distributor distributor = check.getMember().getDistributor();
            if (distributor != null) {
                check.setActivationFlag(true);
                distributor.setLevel(check.getDistributorLevel());
                distributorRepository.save(distributor);
            }
        }
        distributionCheckRepository.save(check);
    }

    /**
     * 批量审核分销商
     */
    public void allCheck(String data) {
        List<String> ids = Splitter.on(data).omitEmptyStrings().trimResults().splitToList(data);
        for (String id : ids) {
            check(new DistributionCheck().setId(NumberUtils.toLong(id)).setCheckNote("批量审核").setCheckStatus(2));
        }
    }

    /**
     * 激活
     */
    public void activation(DistributionCheck distributionCheck) {

        distributionCheck.setActivationFlag(true);
        distributionCheckRepository.save(distributionCheck);

        WebUser member = distributionCheck.getMember();
        Distributor distributor = member.getDistributor();

        if (distributor == null) {
            distributor = new Distributor();
            DistributionSetting setting = distributionSettingApplication.findLastSetting();
            distributor.setMicroShop(setting != null && BooleanUtils.isTrue(setting.getDistributorAutoOpenShop()));
            distributor.setUser(member);
            distributor.setSource(member.getFather() != null ? 1 : 3);
            distributor.setCreateTime(new Timestamp(System.currentTimeMillis()));
            distributor.setAccountStatus(1);
        }

        if (member.getFather() == null && distributionCheck.getDistributorId() != null) {
            member.setFather(queryChannelService.findOne(QWebUser.webUser.distributor.id.eq(distributionCheck.getDistributorId()), WebUser.class));
        }

        distributor.setLevel(distributionCheck.getDistributorLevel());
        distributorRepository.save(distributor);

        member.setDistributor(distributor);
        webUserRepository.save(member);

        //给每个分销商添加 分销商品池里面的指定所有分销商的商品
        List<DistributionGoods> distributionGoodsList = queryChannelService.findAll(QDistributionGoods.distributionGoods.distributorScope.eq(1), DistributionGoods.class);

        //已存在的不添加
        long did = distributor.getId();
        distributionGoodsList.removeIf(g -> queryChannelService.selectCount("select count(*) from distribution_goods_assign where distributionGoods = :gid and distributor_id = :did", ImmutableMap.of("gid", g.getId(), "did", did)) > 0);

        if (CollectionUtils.isNotEmpty(distributionGoodsList)) {
            distributorAddScopeAllGoods(distributionGoodsList, distributor);
        }

    }


    /**
     * 新增分销商 分销商品池里面的指定所有分销商的商品
     *
     * @param distributionGoodsList 分销池为所有分销商的商品列表
     * @param distributor           新增的分销商
     */
    private void distributorAddScopeAllGoods(List<DistributionGoods> distributionGoodsList, Distributor distributor) {

        for (DistributionGoods distributionGoods : distributionGoodsList) {
            DistributionGoodsAssign distributionGoodsAssign = new DistributionGoodsAssign();
            distributionGoodsAssign.setDistributionGoods(distributionGoods);
            distributionGoodsAssign.setDistributor(distributor);

            Goods goods = distributionGoods.getGoods();
            distributionGoodsAssign.setThirdChannel(goods.getGoodsChannel().getId());
            distributionGoodsAssign.setSecondChannel(goods.getGoodsChannel().getParent().getId());
            distributionGoodsAssign.setFirstChannel(goods.getGoodsChannel().getParent().getParent().getId());
            distributionGoodsAssignRepository.save(distributionGoodsAssign);
        }

    }

    public void modifyBackground(Distributor distributor, String value) {
        distributor.setShopBackgroundImage(value);
        distributorRepository.save(distributor);
    }

    public void modifyShopName(Distributor distributor, String value) {
        distributor.setShopName(value);
        distributorRepository.save(distributor);
    }

    public void modifyNickname(WebUser user, String value) {
        user.setNickname(value);
        webUserRepository.save(user);
    }

    public void modifyQQ(WebUser user, String value) {
        user.setQq(value);
        webUserRepository.save(user);
    }

    /**
     * 分销商选择全部商品
     *
     * @param distributor 分销商
     */
    public void selectAllGoods(Distributor distributor) {
        List<DistributionGoodsAssign> all = queryChannelService.findAll(QDistributionGoodsAssign.distributionGoodsAssign.distributor.id.eq(distributor.getId()), DistributionGoodsAssign.class);
        for (DistributionGoodsAssign assign : all) {
            assign.setStatus(1);
        }
        distributionGoodsAssignRepository.save(all);

        distributor.setChannelIds(null);
        distributorRepository.save(distributor);
    }

    /**
     * 分销商选择指定分类商品
     *
     * @param distributor 分销商
     * @param ids         三级分类id
     */
    public void selectChannelGoods(Distributor distributor, String ids) {

        List<Long> longIds = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(ids).stream().map(Long::valueOf).collect(Collectors.toList());

        List<DistributionGoodsAssign> all = queryChannelService.findAll(QDistributionGoodsAssign.distributionGoodsAssign.distributor.id.eq(distributor.getId()), DistributionGoodsAssign.class);
        for (DistributionGoodsAssign assign : all) {
            if (longIds.contains(assign.getThirdChannel())) {
                assign.setStatus(1);
            } else {
                assign.setStatus(null);
            }
        }
        distributionGoodsAssignRepository.save(all);

        distributor.setChannelIds(ids);
        distributorRepository.save(distributor);
    }

    /**
     * 分销商选择指定商品
     *
     * @param distributor 分销商
     */
    public void selectGoods(Distributor distributor, String ids) {

        List<Long> longIds = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(ids).stream().map(Long::valueOf).collect(Collectors.toList());

        List<DistributionGoodsAssign> all = queryChannelService.findAll(QDistributionGoodsAssign.distributionGoodsAssign.distributor.id.eq(distributor.getId()), DistributionGoodsAssign.class);
        for (DistributionGoodsAssign assign : all) {
            if (longIds.contains(assign.getId())) {
                assign.setStatus(1);
            } else {
                assign.setStatus(null);
            }
        }
        distributionGoodsAssignRepository.save(all);

        distributor.setChannelIds(null);
        distributorRepository.save(distributor);
    }

    /**
     * 绑定邀请人
     */
    public void bindInvitePeople(String userId, long id) {
        WebUser webUser = queryChannelService.findOne(Distributor.class, NumberUtils.toLong(userId)).getUser();
        webUser.setFather(queryChannelService.findOne(WebUser.class, id));
        webUserRepository.save(webUser);
    }

    /**
     * 批量绑定邀请人
     */
    public void bindInvitePeoples(List<String> ids, long id) {
        for (String s : ids) {
            bindInvitePeople(s, id);
        }
    }

    /**
     * 删除分销商下级
     */
    public void removeSubordinate(long id) {
        WebUser webUser = queryChannelService.findOne(WebUser.class, id);
        webUser.setFather(null);
        webUserRepository.save(webUser);
    }

    /**
     * 添加分销商下级
     */
    public void addSubordinate(long id, long userId) {
        WebUser webUser = queryChannelService.findOne(Distributor.class, userId).getUser();
        WebUser user = queryChannelService.findOne(WebUser.class, id);
        user.setFather(webUser);
        webUserRepository.save(user);
    }
}
